package c_011;

import java.util.concurrent.*;

/**
 * @Classname TestPool
 * @Description 自定义线程池
 * @Date 2023/3/30 23:55
 * @Created by 86182
 */
public class TestPool {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1. 构建线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2,
                2,
                0,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(1),
                r -> {
                    Thread thread = new Thread(r);
                    thread.setName("szzt-ThreadPoolExecutor");
                    return thread;
                },
                new MyRejectedExecution()
        );
        //让线程池处理任务,没返回结果
        threadPool.execute(() -> {
            System.out.println("没有返回结果的任务");
        });

        for (int i = 0; i < 100; i++) {
            try {
                threadPool.execute(()->{
                    System.out.println("没有返回结果的任务111"+Thread.currentThread().getName());
                });
            } catch (Exception e) {
                System.out.println("抛出异常");
            }
        }

        //3. 让线程池处理有返回结果的任务
        Future<String> future = threadPool.submit(() -> {
            System.out.println("我有返回结果！");
            return "返回结果";
        });
        Object result = future.get();
        System.out.println(result);
        threadPool.shutdown();
    }

    private static class MyRejectedExecution implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            System.out.println("根据自己的业务情况，决定编写的代码！");
        }
    }
}
